%%@ author Grupp 3
%%@ version 1.5
%%@ copyright Grupp 3
%%@ doc The module for starting the supervisor server. 

-module(serverCheck).

-export([start/0]).



%%@doc spawns a new server and registers it as server_check, starts mainServer"
%%@spec start() -> atom()

start() ->

	ServerPid = spawn(fun() -> server_Check([]) end),
	register(server_check, ServerPid),
	mainServer:start().


%%@doc waiting for calls to upptade ServerList, after 20000 will start the server_Check_Main/0, server_Check_Help/1 functions then loop
%%@spec server_Check(ServerList) -> any()
%%where
%%	ServerList = {pid(),interger()}

server_Check(ServerList) ->
	receive
		{hello, Id , ClientPid} -> 
			case lists:keysearch(Id,2,ServerList) of 
			false ->
				server_Check(ServerList++[{ClientPid,Id}]);
			_ ->
				server_Check(ServerList)
			end;

		{delete , Id , ClientPid} ->
			server_Check(lists:keydelete(Id,2,ServerList))
	after 2000 ->
	io:format("ServerCheck is still running ~n",[]),
	server_Check_Main(),
	server_Check_Help(ServerList),
	server_Check(ServerList)
end.

%%@doc Sends a ping to all servers in list, if the pinged server don't awnswere it will call the projectServer:start_servers/1 function
%%@spec server_Check_Help(ServerList) -> atom()
%%where 
%%    ServerList = {pid(), interger()}

server_Check_Help([]) -> 
	ok;
	
server_Check_Help([H | T]) ->


	{list_to_atom(hd(io_lib:format("~w",[element(2,H)]))), pronection_server@hamberg.it.uu.se} ! {check , self()},
		receive 
		{ok, ClientPid} -> 
			io:format("ProjectServer ~w is checking in ~n", [element(2,H)]),
			server_Check_Help(T)

		after 2000 ->
			io:format("Project server ~w timed out restarting... ~n", [element(2,H)]),
			
			case lists:filter(fun (X) -> X == list_to_atom(hd(io_lib:format("~w",[element(2,H)]))) end, registered()) of
			[] ->
				projectServer:start_servers([H]),
				server_Check_Help(T);
			_ -> 
				unregister(list_to_atom(hd(io_lib:format("~w",[element(2,H)])))),		
				projectServer:start_servers([H]),
				server_Check_Help(T)
			end
		end.

%%@doc Sends a ping to mainServers ,if the pinged server don't awnswere it will call the mainServer:restart/0 function
%%@spec server_Check_Main() -> atom()

server_Check_Main() ->
  	
	{pronection_server, pronection_server@hamberg.it.uu.se} ! {check , self()},
		receive 
			{ok, ClientPid} ->
				io:format("MainServer checked in ~n", []),
				ok

		after 2000 ->
			io:format("MainServer timed out, restarting... ~n", []),
			case lists:filter(fun (X) -> X == pronection_server end, registered()) of
			[] ->
    				mainServer:restart(),
				ok;
			_ ->
				unregister(pronection_server),
				mainServer:restart()
		end
	end.
		
